import ResultWrap from '@/components/ResultWrap';
import { addUser, getUserDetail, queryDeptList, queryPostAll, queryRoleAll, updateUser } from '@/services/system/SystemController';
import {
  ModalForm,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Form, message } from 'antd';


const UserForm: React.FC<{
  id: number | null;
  onClose: () => void;
  onFinish: () => void;
}> = ({ id, onClose, onFinish }) => {
  const [form] = Form.useForm<System.UserInfo>();

  let { loading: submiting, run: submit } = useRequest((data) => id === null ? Promise.reject("null id") : id != 0 ? updateUser(id, data) : addUser(data), {
    manual: true,
    throwOnError: true,
    onError(e, params) {
      message.error("操作失败")
    },
    onSuccess() {
      onFinish();
    },
  })

  let { loading: loadingUserInfo, run: loadUserInfo, error: errorUserInfo } = useRequest(() => id !== null && id != 0 ? getUserDetail(id) : Promise.resolve({ roles: [], posts: [] }), {
    throwOnError: true,
    refreshDeps: [id],
    onSuccess(d) {
      d.roles = d.roles.map((x: any) => x.id);
      d.posts = d.posts.map((x: any) => x.id);
      form.setFieldsValue(d)
    },
  })

  return (
    <ModalForm<System.UserInfo>
      title={id ? `编辑用户：${form.getFieldValue("username")}` : '新建用户'}
      layout="horizontal"
      open={id !== null}
      form={form}
      width={450}
      autoFocusFirstInput
      modalProps={{ destroyOnClose: true, onCancel: onClose }}
      submitTimeout={2000}
      onFinish={submit}
      loading={submiting}
    >
      <ResultWrap error={errorUserInfo} reload={loadUserInfo}>
        {id === 0 && (<ProFormText name="username" label="登录账号" placeholder="请输入登录账号" rules={[{ required: true, message: '请输入至少三个字符！', min: 3, max: 32, }]} />)}
        <ProFormText name="nickname" label="用户名称" placeholder="请输入用户名称" rules={[{ required: true, message: '请输入至少三个字符！', min: 3, max: 32, }]} />
        <ProFormText name="password" label={id ? '修改密码（可选）' : '登录密码'} tooltip={id ? '填写时，将修改密码' : ''} placeholder={id ? '请输入新密码（可选）' : '请输入登录密码'} rules={[{ required: id === 0, min: 6, max: 32, },]} />
        <ProFormText name="phone" label="手机" placeholder="请输入手机" rules={[{ min: 8, max: 16, }]} />
        <ProFormText name="email" label="Email" placeholder="请输Email" />
        <ProFormSelect name="sex" label="性别" options={[{ value: 0, label: "未知" }, { value: 1, label: "男" }, { value: 2, label: "女" }]} />
        <ProFormSwitch name='status' label="状态" />
        <ProFormTreeSelect name="dept_id" label="上级部门" placeholder="请选择上级部门" required
          fieldProps={{ fieldNames: { label: 'dept_name', value: 'dept_id', } }}
          request={async () => {
            let { data } = await queryDeptList({ status: true });
            return data;
          }}
        />
        <ProFormSelect name="roles" label="角色" placeholder="请选择角色" request={queryRoleAll} fieldProps={{ mode: 'multiple', fieldNames: { label: 'name', value: 'id', } }} />
        <ProFormSelect name="posts" label="岗位" placeholder="请选择岗位" request={queryPostAll} fieldProps={{ mode: 'multiple', fieldNames: { label: 'name', value: 'id', } }} />
      </ResultWrap>
    </ModalForm>
  );
};

export default UserForm;
